package com.cyt.sys.util;

import cn.hutool.core.util.StrUtil;
import com.cyt.sys.model.po.ParamConfig;
import com.cyt.sys.util.cache.ParamConfigUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 关于文件路径的处理
 *
 * @author taocongcong
 * @create 2017-09-04 11:04
 */
public class FilePathUtil {

    /**
     * 单个文件删除(如果附件存在就删除，不存在默认为已删除）
     *
     * @param request HttpServletRequest对象
     * @param path 文件相对路径
     * @return
     * @author shengQiang yu
     * @date 2019-03-07 16:14
     */
    public static void deleteFile(HttpServletRequest request,String path){
        File file=new File(acceptRealPath(request)+path);
        if(file.isFile() &&file.exists()){
            file.delete();
        }
    }

    /**
     * 判断当前文件是否存在
     *
     * @param request HttpServletRequest对象
     * @param path 文件相对路径
     * @return
     * @author shengQiang yu
     * @date 2019-03-07 16:11
     */
    public static boolean checkFile(HttpServletRequest request,String path){
        File file=new File(acceptRealPath(request)+path);
        return file.exists();
    }

    /**
     * 获取相对路径
     *
     * @param request HttpServletRequest对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-07 16:09
     */
    public static String acceptRealPath(HttpServletRequest request){
        return request.getServletContext().getRealPath("/");
    }

    /**
     * 获取相对路径
     *
     * @param request HttpServletRequest对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-07 16:09
     */
    public static String acceptCheckRealPath(HttpServletRequest request){
        ParamConfig fileUploadPath = ParamConfigUtils.getParamConfig("fileUploadPath");
        String realPath = FilePathUtil.acceptRealPath(request);
        if(fileUploadPath!=null&& StrUtil.isNotEmpty(fileUploadPath.getInfo())){
            realPath=fileUploadPath.getInfo();
        }
        return realPath;
    }

}
